import tkinter as tk
from tkinter import *
from tkinter.messagebox import *
import time
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import numpy as np
import matplotlib.animation as animation
import matplotlib.pyplot as plt
from dev.T10 import T10

class chartPage(object):
    def __init__(self, master=None,interval=1000):
        self.root = master
        print(self.root.baudrate)
        self.x = np.array([])
        self.y = np.array([])
        self.anim = None
        self.interval = interval
        #self.createPage()
    def init(self):
        self.ax.plot(self.x,self.y,ls = '-',marker = 'o', color = 'blue')  # 绘制新的图
        self.ax.set_xlabel('Time(s)')
        self.ax.set_ylabel('Temp(℃)')
        self.ax.set_title('Temperature Curve')
        self.ax.grid(True)
        self.canvas.draw()  # 重绘图表
    # 定义动态更新的数据函数
    def update_data(self,frame):
        t10 = T10(self.root.port,self.root.baudrate,self.root.slave)
        d = t10.read_reg()
        if d == []:
            self.anim.event_source.stop()
            showinfo(title='提示', message='无法读取数据')
        else:
            self.label.config(text='实时数据: '+str(d))
            self.x = np.append(self.x, time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
            self.y = np.append(self.y, d[4])
            if len(self.y) > 30:
                self.y = self.y[1:]
                self.x = self.x[1:]
        return self.x, self.y
    
    # 定义绘制图表的函数
    def plot_curve(self,frame):
        x,y = self.update_data(frame)
        self.ax.clear()  # 清除之前的图
        self.ax.plot(x,y,ls = '-',marker = 'o',color = 'blue')  # 绘制新的图
        self.ax.set_xlabel('Time(s)')
        self.ax.set_ylabel('Temp(℃)')
        self.ax.set_title('Temperature Curve')
        self.ax.grid(True)
        self.canvas.draw()  # 重绘图表
    def createPage(self):
        self.newWindow = tk.Toplevel(self.root)
        self.newWindow.title("Chart")
        self.newWindow.geometry("800x600")
        self.label = tk.Label(self.newWindow, text='实时数据: ')
        self.label.pack()
        # 初始化Figure和FigureCanvas
        self.fig = Figure(figsize=(5, 5), dpi=100)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.newWindow)
        self.canvas.draw()
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        # 创建一个图表和一个轴
        self.ax = self.fig.add_subplot(1,1,1)

        # 使用FuncAnimation来动态更新图表
        self.anim = animation.FuncAnimation(self.fig, self.plot_curve,init_func=self.init, frames=2, interval=self.interval,repeat_delay=self.interval)